package controllers.admin;

import java.util.ArrayList;
import java.util.List;

import controllers.GlobalVariables;
import controllers.Secure;
import controllers.ValidationUtil;

import models.Administrator;
import models.Attachment;
import models.Batch;
import models.Brand;
import models.Commodity;
import models.Message;
import models.QueryBean;
import models.User;
import models.BaseEntity.Status;
import models.Message.MessageType;
import play.data.validation.Valid;
import play.db.jpa.GenericModel.JPAQuery;
import play.mvc.*;

@With(Secure.class)
public class Brands extends Controller {

	public static void index(){
		render();
	}
	
	public static void indexTable(QueryBean queryBean) {
		if(queryBean == null) {
			queryBean = new QueryBean();
			queryBean.isDesc = true;
		}
		StringBuilder hql = new StringBuilder("id != null ");
    	List<Object> objs = new ArrayList<Object>();
    	
    	if(!ValidationUtil.isEmpty(queryBean.keyword)) {
    		if(ValidationUtil.isLong(queryBean.keyword)) {
    			hql.append("and (id=? or");
        		objs.add(queryBean.keyword);
    		} else {
    			hql.append("and (");
    		}
    		hql.append("name like ? or common like ?) ");
    		objs.add("%"+queryBean.keyword+"%");
    		objs.add("%"+queryBean.keyword+"%");
    	}
    	
    	if(!ValidationUtil.isEmpty(queryBean.orderby)) {
    		hql.append(" order by " + queryBean.orderby);
    		if(queryBean.isDesc) 
    			hql.append(" desc ");
    		else
    			hql.append(" asc ");
    	} else {
    		hql.append(" order by createAt desc, lastModifiedAt desc ");
    	}
		
		//页数计算
		queryBean.totalQuantity = Brand.count(hql.toString(), objs.toArray());
		queryBean.totalPage = (queryBean.totalQuantity/queryBean.quantityEachPage + 1);
		if(queryBean.totalPage < queryBean.currentPage) {
			queryBean.currentPage = queryBean.totalPage;
		}
		
		List<Brand> brands = Brand.find(hql.toString(), objs.toArray()).fetch(
				(int)queryBean.currentPage, queryBean.quantityEachPage);
		
		render(brands, queryBean);
	}
	
	/**
	 * 跳转到编辑品牌页面。
	 * @param id
	 */
	public static void show(Long id){
		Brand brand = new Brand();
		if(id != null) {
			brand = Brand.findById(id);
		}
		render(brand);
	}
	
	/**
	 * 更新品牌数据。
	 * @param brand
	 */
	public static void update(@Valid Brand brand) {
		if(validation.hasErrors()) {
			params.flash();
			validation.keep();
			render("@show", brand);
		}
		Brand brandOri = Brand.findById(brand.id);
		if(brandOri == null) {
			validation.addError("brand.id", "此品牌已经被删除。");
			render("@show", brand);
		}
		
		String username = session.get(GlobalVariables.SECURE_ADMINNAME);
		Administrator admin = Administrator.find("byUsername", username).first();
		
		if(brandOri.image != null) {
			if(brandOri.image.id != brand.image.id) {
				brandOri.image.used = false;
				brandOri.resetModifier(admin);
				brandOri.image.save();
				brandOri.image = Attachment.findById(brand.image.id);
				brandOri.image.used = true;
				brandOri.resetModifier(admin);
				brandOri.image.save();
			}
		}
		brandOri.name = brand.name;
		brandOri.common = brand.common;
		brandOri.resetModifier(admin);
		brandOri.save();
		index();
	}
	
	/**
	 * 新建品牌页面。
	 */
	public static void newBrand() {
		Brand brand = new Brand();
		render("@new", brand);
	}
	
	/**
	 * 更新品牌数据。
	 * @param brand
	 */
	public static void create(@Valid Brand brand) {
		if(validation.hasErrors()) {
			params.flash();
			validation.keep();
			render("@new", brand);
		}
		
		String username = session.get(GlobalVariables.SECURE_ADMINNAME);
		Administrator admin = Administrator.find("byUsername", username).first();
		
		Attachment image = Attachment.findById(brand.image.id);
		image.used = true;
		image.resetModifier(admin);
		image.save();
		
		brand.image = image;
		brand.setCreator(admin);
		brand.resetModifier(admin);
		brand.save();
		index();
	}
	
	/**
	 * 把品牌设置为无效。
	 */
	public static void updateBrandStatus(long id, Status status) {
		Brand brand = Brand.findById(id);
		if(brand == null) {
			throw new RuntimeException("此品牌("+id+")已经被删除。");
		}
		String username = session.get(GlobalVariables.SECURE_ADMINNAME);
		Administrator admin = Administrator.find("byUsername", username).first();
		
		brand.status = status;
		brand.resetModifier(admin);
		brand.save();
	}
}
